package com.jp.knowledge.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.google.gson.internal.LinkedTreeMap;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.activity.JpApplicationWebActivity;
import com.jp.knowledge.activity.JpMainActivity;
import com.jp.knowledge.activity.LoginActivity;
import com.jp.knowledge.activity.SearchSimpleActivity;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.dialog.ExperienceAllGroupDialog;
import com.jp.knowledge.dialog.ExperienceMergedDialog;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.logic.ExperienceLogic;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.model.experience.ExperienceModel;
import com.jp.knowledge.model.experience.TiyanApps;
import com.jp.knowledge.util.JsonUtil;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.experience.ExperienceClassifyView;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/1/19.
 */

public class ExperienceFragment extends BaseFragment implements View.OnClickListener,
        ExperienceClassifyView.EditStateChangeListener,
        ExperienceClassifyView.IconClickListener, CanRefreshLayout.OnRefreshListener,
        ResultSubscriber.OnResultListener {

    private List<List<TiyanApps>> classifyData;
    private ExperienceLogic experienceLogic;

    @ViewInject(R.id.experience_edit_view)
    private LinearLayout experienceEditView;
    @ViewInject(R.id.experience_edit_merged)
    private TextView experienceEditMerged;
    @ViewInject(R.id.experience_edit_remove)
    private TextView experienceEditRemove;
    @ViewInject(R.id.experience_edit_delete)
    private TextView experienceEditDelete;
    @ViewInject(R.id.experience_edit_btn)
    private TextView experienceEditBtn;
    @ViewInject(R.id.experience_empty_to_add)
    private ImageView emptyToAddBtn;
    @ViewInject(R.id.refresh)
    private CanRefreshLayout refreshLayout;
    @ViewInject(R.id.can_content_view)
    private ExperienceClassifyView classifyView;

    private CommDialog deleteDialog;
    private ExperienceMergedDialog mergeDialog;
    private ExperienceAllGroupDialog groupDialog;

    private String myExperiencePath;
    private String myLastTiyanPath;
    private FileCacheManager cacheManager;
    private Subscriber readCacheSubscribe;
    private OnSubscribe readCacheOnSubscribe;

    private BroadcastReceiver broadcastReceiver;
    private LocalBroadcastManager localBroadcastManager;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View contentView = inflater.inflate(R.layout.fragment_experience, null);
        x.view().inject(this, contentView);
        initHead(contentView);
        initData();
        initTitle();
        initView();
        initDialog();
        initCacheData();
        initBroadCast();
        readCache();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            View topBar = contentView.findViewById(R.id.top_bar);
            int statusBarHeight = 0;
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0)
                statusBarHeight = getResources().getDimensionPixelSize(resourceId);
            topBar.setPadding(0, statusBarHeight, 0, 0);
        }
        return contentView;
    }

    private void initData(){
        this.classifyData = new ArrayList<>();
        this.experienceLogic = new ExperienceLogic(mContext);
    }

    private void initCacheData(){
        this.cacheManager = new FileCacheManager();
        this.myLastTiyanPath = mContext.getCacheDir()+"/myLastTiyan_" + HttpHelper.uuid + ".dat";
        this.myExperiencePath = mContext.getCacheDir()+"/myExperience_" + HttpHelper.uuid + ".dat";
        this.readCacheOnSubscribe = new OnSubscribe<List<List<TiyanApps>>>(){
            @Override
            public void call(Subscriber<? super List<List<TiyanApps>>> subscriber) {
                List<List<TiyanApps>> cacheExperience = (List<List<TiyanApps>>) cacheManager.readObject(myExperiencePath);
                subscriber.onNext(cacheExperience);
            }
        };
        this.readCacheSubscribe = new Subscriber<List<List<TiyanApps>>>() {
            @Override
            public void onCompleted() {
                classifyView.notifyDataSetChanged();
                getMyExperience();
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext(List<List<TiyanApps>> data) {
                if(data != null && data.size() > 0){
                    classifyData.clear();
                    classifyData.addAll(data);
                } else{
                    updateClassifyView(new ArrayList<ExperienceModel>());
                }
                onCompleted();
            }
        };
    }

    private void initTitle(){
        topName.setText("体验");
        topDesc.setText("快速分析每个产品");
        rightIcon.setOnClickListener(this);
        mostRightIcon.setOnClickListener(this);
        rightIcon.setImageResource(R.mipmap.guanzhutianjia);
        rightIcon.setVisibility(View.VISIBLE);
        mostRightIcon.setVisibility(View.GONE);
    }

    private void initView(){
        emptyToAddBtn.setOnClickListener(this);
        experienceEditBtn.setOnClickListener(this);
        experienceEditMerged.setOnClickListener(this);
        experienceEditRemove.setOnClickListener(this);
        experienceEditDelete.setOnClickListener(this);
        refreshLayout.setRefreshEnabled(false);
        refreshLayout.setLoadMoreEnabled(false);
        refreshLayout.setOnRefreshListener(this);
        classifyView.setAdapter(classifyData);
        classifyView.setEditStateChangeListener(this);
        classifyView.setIconClickListener(this);
        classifyView.setNotifyDataSetChangedListener(new ExperienceClassifyView.NotifyDataSetChangedListener() {
            @Override
            public void onDataSetChanged(List<List<TiyanApps>> classifyData) {
                saveDataToCache(classifyData, myExperiencePath);
            }
        });
        classifyView.setActionHappenedListener(new ExperienceClassifyView.ActionHappenedListener() {
            @Override
            public void groupCreated(List<TiyanApps> groupData) {
                experienceLogic.groupCreated(groupData);
            }
            @Override
            public void groupRename(String name, String groupId) {
                experienceLogic.groupRename(name, groupId);
            }
            @Override
            public void iconsMoveIn(List<String> iconsId, String groupId) {
                experienceLogic.iconsMoveIn(iconsId, groupId);
            }
            @Override
            public void iconsMoveOut(List<String> iconsId, String groupId) {
                experienceLogic.iconsMoveOut(iconsId, groupId);
            }
            @Override
            public void dataDelete(List<String> mids) {
                experienceLogic.dataDelete(mids);
            }
            @Override
            public void dataSorted(List<List<TiyanApps>> data) {
                experienceLogic.dataSorted(data);
            }
        });
    }

    private void initDialog(){
        mergeDialog = new ExperienceMergedDialog(mContext);
        mergeDialog.setCancelable(true);
        mergeDialog.setRightListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for(List<TiyanApps> mergeDatas : classifyData){
                    if(mergeDatas != null && mergeDatas.size() > 1
                            && mergeDialog.getEditText().equals(mergeDatas.get(0).getGName())){
                        ToasUtil.toast(mContext, "抱歉，该组已存在，请输入合适的组名");
                        return;
                    }
                }
                classifyView.mergeAllCheckIcon(mergeDialog.getEditText());
                mergeDialog.dismiss();
            }
        });
        deleteDialog = new CommDialog(mContext);
        deleteDialog.setContent("是否删除选中的应用？");
        deleteDialog.setRightListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                classifyView.deleteAllCheckIcon();
            }
        });
        groupDialog = new ExperienceAllGroupDialog(mContext);
        groupDialog.setGroupSelectedListener(new ExperienceAllGroupDialog.GroupSelectedListener() {
            @Override
            public void onGroupSelected(int groupPosition) {
                classifyView.moveAllCheckIconToGroup(groupPosition);
            }
        });
    }

    private void initBroadCast() {
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if(action.equals(LocalBroadCast.LOGOUT_SUCCESS_BROD)){          // 退出登陆
                    updateClassifyView(new ArrayList<ExperienceModel>());
                } else if(action.equals(LocalBroadCast.ADD_EXP_APP)){            // 添加新体验
                    List<ExperienceModel> addApps = (List<ExperienceModel>) intent.getSerializableExtra("appData");
                    String gid = intent.getStringExtra("gid");
                    List<List<TiyanApps>> addTiyanApps = formatDataForClassify(addApps);
                    if(addTiyanApps == null || addTiyanApps.size() == 0)
                        return;
                    if(gid != null && gid.trim().length() > 0){
                        for(List<TiyanApps> groupData : classifyData){
                            if(groupData == null || groupData.size() == 0)
                                continue;
                            if(gid.equals(groupData.get(0).getGid())){
                                TiyanApps addApp = null;
                                if(groupData.get(groupData.size()-1).getPid().equals("add"))
                                    addApp = groupData.remove(groupData.size()-1);
                                for(List<TiyanApps> apps : addTiyanApps) {
                                    if(apps == null || apps.size() == 0)
                                        continue;
                                    for(TiyanApps app : apps){
                                        app.setGid(groupData.get(0).getGid());
                                        app.setGName(groupData.get(0).getGName());
                                        app.setParentMid(groupData.get(0).getParentMid());
                                    }
                                    groupData.addAll(apps);
                                }
                                if(addApp != null)
                                    groupData.add(addApp);
                                classifyView.getAdapter().getSubAdapter().notifyDataSetChanged();
                                classifyView.notifyDataSetChanged();
                                return;
                            }
                        }
                    }
                    classifyData.addAll(0, addTiyanApps);
                    classifyView.notifyDataSetChanged();

                    if(emptyToAddBtn.getVisibility() != View.GONE)
                        emptyToAddBtn.setVisibility(View.GONE);
                    if(refreshLayout.getVisibility() != View.VISIBLE)
                        refreshLayout.setVisibility(View.VISIBLE);

                } else if(action.equals(LocalBroadCast.GET_MY_EXPERIENCE_CODE)
                        || action.equals(LocalBroadCast.LOGIN_SUCCESS_BROD)){
                    getMyExperience();
                } else if(action.equals(LocalBroadCast.CONNECT_NET_BROAD) && classifyData.size() == 0){
                    getMyExperience();
                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocalBroadCast.GET_MY_EXPERIENCE);
        intentFilter.addAction(LocalBroadCast.GET_LAST_EXPERIENCE);
        intentFilter.addAction(LocalBroadCast.LOGOUT_SUCCESS_BROD);
        intentFilter.addAction(LocalBroadCast.ADD_EXP_APP);
        intentFilter.addAction(LocalBroadCast.GET_MY_EXPERIENCE_CODE);
        intentFilter.addAction(LocalBroadCast.LOGIN_SUCCESS_BROD);
        intentFilter.addAction(LocalBroadCast.CONNECT_NET_BROAD);
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        localBroadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(broadcastReceiver);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.icon_serach:                   // 搜索
//                SearchSimpleActivity.gotoSearch(getContext(), 8, "joinExp", true);
//                break;
            case R.id.icon_right:
            case R.id.experience_empty_to_add:      // 添加新图标
//                if(gotoLogin())
//                    return;
//                if(classifyView.getEditState())
//                    classifyView.setEdit(false);
//                JpApplicationWebActivity.gotoWebActivity(context, "library/ProductList?recommendAction=exp");
//                break;
                SearchSimpleActivity.gotoSearch(getContext(), 8, -1, "joinExp", true);
                break;
            case R.id.experience_edit_btn:          // 编辑
                if(classifyData.size() == 0 && !classifyView.getEditState())
                    onClick(emptyToAddBtn);
                else
                    classifyView.setEdit(!classifyView.getEditState());
                break;
            case R.id.experience_edit_merged:       // 合并新组
                if(classifyView.getIconCheckNum() > 1)
                    mergeDialog.show();
                else
                    ToasUtil.toast(mContext, "请最少勾选两个应用");
                break;
            case R.id.experience_edit_remove:       // 移入组
                if(classifyView.getIconCheckNum() > 0)
                    groupDialog.show(classifyData, classifyView.getAllGroupPosition());
                break;
            case R.id.experience_edit_delete:       // 删除
                if(classifyView.getIconCheckNum() > 0)
                    deleteDialog.show();
                break;
        }
    }

    /* 编辑状态改变回调 */
    @Override
    public void onEditStateChange(boolean isEdit) {
        if (isEdit) {
            experienceEditBtn.setText("完成");
            experienceEditView.setVisibility( View.VISIBLE);
        } else{
            experienceEditBtn.setText("编辑");
            experienceEditView.setVisibility(View.GONE);
            if(classifyData.size() == 0){
                emptyToAddBtn.setVisibility(View.VISIBLE);
                refreshLayout.setVisibility(View.GONE);
            }
            saveDataToCache(classifyData, myExperiencePath);
        }
    }

    /* 图标单击回调 */
    @Override
    public void onIconClick(int parentIndex, int index) {
        if(classifyData.get(parentIndex).get(index).getPid().equals("add"))
            JpApplicationWebActivity.gotoWebActivity(mContext, "library/ProductList?recommendAction=exp&groupId="
                    + classifyData.get(parentIndex).get(0).getGid());
        else if(classifyData.get(parentIndex).get(index).getIsExp() == 1)
            JpApplicationWebActivity.gotoWebActivity(mContext,
                    "details/experienceDetails?id=" + classifyData.get(parentIndex).get(index).getPid());
        else
            JpApplicationWebActivity.gotoWebActivity(mContext,
                    "details/productDetails?id=" + classifyData.get(parentIndex).get(index).getPid() + "&tabIndex=0");
    }

    @Override
    public void onRefresh() {
        mContext.sendBroadcast(new Intent(LocalBroadCast.GET_MY_EXPERIENCE_CODE));
    }

    /* 从缓存中读取数据 */
    private void readCache(){
        Observable.create(readCacheOnSubscribe)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(readCacheSubscribe);
    }

    /* 将数据更新到视图中 */
    private void updateClassifyView(List<ExperienceModel> experienceModels){
        classifyData.clear();
        List<List<TiyanApps>> formatedDatas = formatDataForClassify(experienceModels);
        if(application.getUserData() == null || application.getUserData().getIsLogin() != 1)
            formatedDatas.clear();
        if(experienceModels.size() == 0 || formatedDatas.size() == 0) {
            emptyToAddBtn.setVisibility(View.VISIBLE);
            refreshLayout.setVisibility(View.GONE);
        } else{
            classifyData.addAll(formatedDatas);
            emptyToAddBtn.setVisibility(View.GONE);
            refreshLayout.setVisibility(View.VISIBLE);
        }
        classifyView.notifyDataSetChanged();
    }

    /* 跳转到登录界面 */
    protected boolean gotoLogin(){
        UserData userData = application.getUserData();
        if(userData == null || userData.getIsLogin() != 1
                || userData.getUuid().trim().length() == 0) {
            ToasUtil.toast(mContext, "请登录后再添加体验产品");
            mContext.startActivity(new Intent(mContext, LoginActivity.class));
            return true;
        }
        return false;
    }

    /* 转换数据格式 */
    private List<List<TiyanApps>> formatDataForClassify(List<ExperienceModel> experienceModels){
        List<List<TiyanApps>> formatedDatas = new ArrayList<>();
        for(ExperienceModel experienceModel : experienceModels){
            List<TiyanApps> groupData = new ArrayList<>();
            if(experienceModel.getType() == 1){             // 体验产品
                TiyanApps apps = new TiyanApps();
                apps.setPid(experienceModel.getPid());
                apps.setPName(experienceModel.getPName());
                apps.setDesc(experienceModel.getDesc());
                apps.setSize(experienceModel.getSize());
                apps.setIcon(experienceModel.getIcon());
                apps.setUpdate(experienceModel.getUpdate());
                apps.setIsExp(experienceModel.getIsExp());
                apps.setMid(experienceModel.getMid());
                apps.setParentMid(experienceModel.getMid());
                apps.setGid(experienceModel.getGid());
                apps.setGName(experienceModel.getGName());
                apps.setIsCheck(false);
                groupData.add(apps);
            } else if(experienceModel.getType() == 2){      // 体验组
                for (ExperienceModel.AppsBean appBean : experienceModel.getApps()){
                    TiyanApps apps = new TiyanApps();
                    apps.setPid(appBean.getPid());
                    apps.setPName(appBean.getPName());
                    apps.setDesc(appBean.getDesc());
                    apps.setSize(appBean.getSize());
                    apps.setIcon(appBean.getIcon());
                    apps.setUpdate(appBean.getUpdate());
                    apps.setIsExp(appBean.getIsExp());
                    apps.setMid(appBean.getMid());
                    apps.setParentMid(experienceModel.getMid());
                    apps.setGid(experienceModel.getGid());
                    apps.setGName(experienceModel.getGName());
                    apps.setIsCheck(false);
                    groupData.add(apps);
                }
            }
            if(groupData.size() > 0)
                formatedDatas.add(groupData);
        }
        return formatedDatas;
    }

    private final static int GET_MY_EXPERIENCE_CODE = 0x01;       // 获取我的体验列表
    private final static int GET_MY_LAST_EXPERIENCE_CODE = 0x02; // 获取最近体验列表
    /* 获取我的体验数据 */
    private void getMyExperience(){
        HttpHelper.getInstance(mContext).myExperience(new JsonObject(), GET_MY_EXPERIENCE_CODE, this);
    }
    /* 获取最近体验数据 */
    private void getMyLastEexperince(){
        HttpHelper.getInstance(mContext).myExperience(new JsonObject(), GET_MY_LAST_EXPERIENCE_CODE, this);
    }
    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {}
    @Override
    public void onError(int requestType) {
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            onError(requestType);
        } else if(requestType == GET_MY_EXPERIENCE_CODE){
            handleMyExperience(data);
        } else if(requestType == GET_MY_LAST_EXPERIENCE_CODE){
            handleMyLateExperience(data);
        }
    }
    /* 处理我的体验 */
    private void handleMyExperience(IModel data){
        List<ExperienceModel> datas = new ArrayList<>();
        List<Map<String, Object>> list = (List<Map<String, Object>>) data.getData();
        List<String> emptyGroupMids = new ArrayList<>();
        for(int i = 0; i < list.size(); i++){
            LinkedTreeMap<String, Object> treeMap = new LinkedTreeMap<>();
            Iterator iter = list.get(i).entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                treeMap.put((String) entry.getKey(), entry.getValue());
            }
            ExperienceModel apps = JsonUtil.getInstance().mapToObject(treeMap, ExperienceModel.class);
            if(apps.getType() == 2 && (apps.getApps() == null || apps.getApps().size() == 0)){
                emptyGroupMids.add(apps.getMid());
                continue;
            }
            if(apps != null)
                datas.add(apps);
        }
        experienceLogic.dataDelete(emptyGroupMids);     // 删除空组
        updateClassifyView(datas);
    }
    /* 处理最近体验 */
    private void handleMyLateExperience(IModel data){

    }
    /* 缓存数据到本地 */
    private void saveDataToCache(final Object data, final String path){
        new Thread(new Runnable() {
            @Override
            public void run() {
                cacheManager.wirteObject(data, path);
            }
        }).start();
    }
}
